const execa = require("execa");
const logInfo = require('../../../util/logInfo');
const logStep = require('../../../util/logStep');

exports.installDeps = async function installDeps(
  targetDir,
  command,
  packageName
) {
  logInfo(
    "安装步骤这里,兼容了 yarn/pnpm/npm 三种方式,大量的处理是对这三种包管理器的兼容处理,主要步骤:0. 验证安装命令是否合法。。2. 执行安装命令。3. 显示安装进度"
  );
  logStep("3.5.1 获取安装命令、可选设置 仓库源的地址例如 taobao");
  const args = ["install", "--loglevel", "error"];
  args.push(packageName)
  logStep("3.5.2  执行安装命令");
  await executeCommand(command, args, targetDir);
  logStep("3.5.3 获取安装进度");
};

function executeCommand(command, args, targetDir) {
  return new Promise((resolve, reject) => {
    console.log(command, args);
    const child = execa(command, args, {
      cwd: targetDir,
      stdio: ["inherit", "pipe", "pipe"],
    });
    child.stdout.on("data", (buffer) => {
      let str = buffer.toString().trim();
      // console.log(str);
      process.stdout.write(str);
    });
    child.on("close", (code) => {
      logInfo("依赖安装结果：" + code);
      if (code !== 0) {
        reject(`command failed: ${command} ${args.join(" ")}`);
        return;
      }
      resolve();
    });
  });
}
